<template>
  <MyModal ref="myModal" title="订单退款" :top="35">
    <template #content>
      <a-form ref="formRef" :rules="rules" :model="formState" :label-col="labelCol">
        <a-form-item label="订单号" name="orderNumber">
          <a-input v-model:value="formState.orderNumber" disabled></a-input>
        </a-form-item>

        <a-form-item label="用户" name="userName">
          <a-input v-model:value="formState.userName" disabled></a-input>
        </a-form-item>

        <a-form-item label="整单出票价" name="finalPrice">
          <a-input v-model:value="formState.finalPrice" disabled></a-input>
        </a-form-item>

        <a-form-item label="退款金额" name="refundBalance">
          <a-input-number
            v-model:value="formState.refundBalance"
            style="width: 50%"
          ></a-input-number>
        </a-form-item>

        <!-- <a-form-item label="退款理由" name="reason">
          <a-textarea
            v-model:value="formState.reason"
            :auto-size="{ minRows: 2, maxRows: 4 }"
            placeholder="退款理由"
            allow-clear
          />
        </a-form-item> -->

        <a-form-item style="padding-left: 44%">
          <a-button style="margin-right: 10px" @click="myModal.cancelModal()">取消</a-button>
          <a-button type="primary" @click="handleSubmit">确定</a-button>
        </a-form-item>
      </a-form>
    </template>
  </MyModal>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { message } from 'ant-design-vue'
import { timeFormat, toYuan, regYuanToFen } from '@/hooks/util'
import * as orderApi from '@/api/order'

const myModal = ref()
const info = ref<any>({})

const showModal = (record: any) => {
  myModal.value?.showModal()
  info.value = record
  formState.value.orderNumber = record.orderNumber
  formState.value.userName = record.userName
  formState.value.finalPrice = toYuan(record.orderFinalPrice * info.value.seatCount)
}

const formRef = ref()

let labelCol = { span: 4 }

interface FormState {
  orderNumber: string
  userName: string
  refundBalance: number
  reason: string
  finalPrice: string
}

const formState = ref<FormState>({
  orderNumber: '',
  userName: '',
  finalPrice: '0',
  refundBalance: 0,
  reason: '',
})

import type { RuleObject } from 'ant-design-vue/es/form/interface'
let validateChangeBalance = async (rule: RuleObject, value: string) => {
  value = String(value)

  if (regYuanToFen(value, 100) > info.value.orderFinalPrice * info.value.seatCount) {
    return Promise.reject('退款金额不能大于出票价')
  }

  if (value == null || value.trim() === '') {
    return Promise.reject('金额不能为空')
  }

  // 使用正则表达式来验证金额格式，允许整数和小数点后两位
  const regex = /^\d+(\.\d{1,2})?$/
  if (!regex.test(value)) {
    return Promise.reject('请输入有效的金额（整数或小数点后两位）')
  }

  // 将字符串转换为数字并检查是否大于0
  const amount = parseFloat(value)
  if (isNaN(amount) || amount <= 0) {
    return Promise.reject('请输入大于0的金额')
  }

  // 如果一切正常，返回成功
  return Promise.resolve()
}
import type { Rule } from 'ant-design-vue/es/form'
const rules: Record<string, Rule[]> = {
  refundBalance: [{ required: true, validator: validateChangeBalance, trigger: 'blur' }],
}

const emit = defineEmits<{
  refresh: []
}>()

defineExpose({
  showModal,
})

const handleSubmit = async () => {
  formRef.value.validate().then(async () => {
    let params = {
      finalPrice: info.value.finalPrice,
      orderId: info.value.orderId,
      orderNumber: info.value.orderNumber,
      price: regYuanToFen(formState.value.refundBalance, 100),
      userName: formState.value.userName,
    }
    try {
      const { state, message: msg } = await orderApi.orderRefund(params)
      if (state === 200) {
        message.success('操作成功')
        formRef.value.resetFields()
        myModal.value?.cancelModal()
        emit('refresh')
      } else {
        message.error(msg)
      }
    } catch (error) {
      message.error('网络请求连接失败~')
    }
  })
}
</script>
